const User = require('../models/User');
const { successResponse, errorResponse, paginationResponse } = require('../utils/response');
const logger = require('../utils/logger');

// 获取用户列表
exports.getUsers = async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const skip = (page - 1) * limit;
    const sort = req.query.sort || 'createdAt';
    const order = req.query.order === 'asc' ? 1 : -1;
    
    // 查询条件
    const filter = {};
    if (req.query.name) {
      filter.name = { $regex: req.query.name, $options: 'i' };
    }
    if (req.query.email) {
      filter.email = { $regex: req.query.email, $options: 'i' };
    }
    if (req.query.role) {
      filter.role = req.query.role;
    }
    if (req.query.status) {
      filter.status = req.query.status;
    }

    // 查询用户总数
    const total = await User.countDocuments(filter);
    
    // 查询用户列表
    const users = await User.find(filter)
      .select('-password')
      .sort({ [sort]: order })
      .skip(skip)
      .limit(limit);

    return paginationResponse(res, users, page, limit, total);
  } catch (error) {
    logger.error(`获取用户列表失败: ${error.message}`);
    return errorResponse(res, '获取用户列表失败', 500);
  }
};

// 获取单个用户
exports.getUser = async (req, res) => {
  try {
    const user = await User.findById(req.params.id).select('-password');
    if (!user) {
      return errorResponse(res, '用户不存在', 404);
    }

    return successResponse(res, user, '获取用户成功');
  } catch (error) {
    logger.error(`获取用户失败: ${error.message}`);
    return errorResponse(res, '获取用户失败', 500);
  }
};

// 创建用户
exports.createUser = async (req, res) => {
  try {
    const { username, password, name, email, role, status } = req.body;

    // 检查用户名或邮箱是否已存在
    const existingUser = await User.findOne({ $or: [{ username }, { email }] });
    if (existingUser) {
      if (existingUser.username === username) {
        return errorResponse(res, '用户名已存在', 400);
      }
      return errorResponse(res, '邮箱已存在', 400);
    }

    // 创建新用户
    const newUser = new User({
      username,
      password,
      name,
      email,
      role,
      status
    });

    await newUser.save();

    // 返回创建的用户信息(排除密码)
    const userResponse = {
      id: newUser.id,
      username: newUser.username,
      name: newUser.name,
      email: newUser.email,
      role: newUser.role,
      status: newUser.status
    };

    return successResponse(res, userResponse, '创建用户成功', 201);
  } catch (error) {
    logger.error(`创建用户失败: ${error.message}`);
    return errorResponse(res, '创建用户失败', 500);
  }
};

// 更新用户
exports.updateUser = async (req, res) => {
  try {
    const { name, email, role, status, avatar } = req.body;
    
    // 查找用户
    const user = await User.findById(req.params.id);
    if (!user) {
      return errorResponse(res, '用户不存在', 404);
    }

    // 检查邮箱是否被其他用户使用
    if (email && email !== user.email) {
      const existingUser = await User.findOne({ email });
      if (existingUser) {
        return errorResponse(res, '邮箱已存在', 400);
      }
    }

    // 更新用户信息
    if (name) user.name = name;
    if (email) user.email = email;
    if (role) user.role = role;
    if (status) user.status = status;
    if (avatar) user.avatar = avatar;

    user.updatedAt = Date.now();
    await user.save();

    return successResponse(res, user, '更新用户成功');
  } catch (error) {
    logger.error(`更新用户失败: ${error.message}`);
    return errorResponse(res, '更新用户失败', 500);
  }
};

// 删除用户
exports.deleteUser = async (req, res) => {
  try {
    const user = await User.findById(req.params.id);
    if (!user) {
      return errorResponse(res, '用户不存在', 404);
    }

    // 阻止删除自己
    if (user.id === req.user.id) {
      return errorResponse(res, '不能删除当前登录的用户', 400);
    }

    await user.remove();
    return successResponse(res, null, '删除用户成功');
  } catch (error) {
    logger.error(`删除用户失败: ${error.message}`);
    return errorResponse(res, '删除用户失败', 500);
  }
}; 